package com.module.lemlin.owner

import android.app.Application
import androidx.lifecycle.*
import com.module.lemlin.app.OwnerApplication
import com.module.lemlin.http.*
import kotlinx.coroutines.*

abstract class OwnerViewModel(application: Application) : AndroidViewModel(application) {
    /**
     * 设置http正确码
     * */
    abstract val httpCodeProPer: Int

    /**
     * token过期/401错误时调用
     * */
    abstract fun onTokenOverdue()
}

fun <data : HttpResponseData> OwnerViewModel.setRxLifeScope(
    listener: SubscribeViewModel<data>, block: suspend CoroutineScope.() -> data?,
) = rxLifeScope.launch({
    val data = block() ?: throw CustomException(
        "9999", "总参数为NULL"
    )
    if (data.code != httpCodeProPer) throw CustomException(
        data.code.toString(), data.message
    )
    listener.onSuccess(data)
}, {
    if (it.code == 401) {
        onTokenOverdue()
    }
    listener.onFailure(it)
}, {
    listener.onStart()
})

fun <data> OwnerViewModel.setViewModelScope(
    listener: SubscribeViewModel<data>, block: suspend CoroutineScope.() -> data,
) = viewModelScope.launch {
    listener.onStart()
    try {
        listener.onSuccess(block())
    } catch (e: Throwable) {
        listener.onFailure(e)
    }
}

/**
 * 生成ViewModel的方法
 */
inline fun <reified VM : OwnerViewModel> ownerViewModel(
    owner: ViewModelStoreOwner,
) = ViewModelProvider(
    owner, ViewModelProvider.AndroidViewModelFactory(OwnerApplication.application)
).get(VM::class.java)
